package xiyuan.weibo;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import weibo4j.Friendships;
import weibo4j.Timeline;
import weibo4j.model.Paging;
import weibo4j.model.Status;
import weibo4j.model.StatusWapper;
import weibo4j.model.User;
import weibo4j.model.UserWapper;
import weibo4j.model.WeiboException;
import xiyuan.exception.NullStatusException;

public class WeiboUtil {
	public static List<Long> getFriendsByUID(long uid){
		List<Long> list = new LinkedList<Long>();
		System.out
				.println("正在处理uid: " + uid + "============================");
		String id = uid + "";
		Friendships fm = new Friendships();
		try {
			UserWapper users = fm.getFriendsByID(id);
			int nextCursor = 0;
			while (users.getNextCursor() <= users.getTotalNumber()) {
				nextCursor += 50;
				users.setNextCursor(nextCursor);
				for (User u : users.getUsers()) {
					list.add(Long.parseLong(u.getId()));
					// 将(uid好友id, uid)放入id_friend这个map结构里
				}
			}
			// System.out.println(users.getTotalNumber());
		} catch (WeiboException e) {
			e.printStackTrace();
		}
		
		//select distinct
		Set<Long> set = new HashSet<Long>();
		for (long uidF:list)	set.add(uidF);
		list = new LinkedList<Long>();
		for (long uidF:set)	list.add(uidF);
		return list;
	}
	
	public static List<Status> getStstusListByUID(long uid) throws InterruptedException{

		List<Status> statuslist = new ArrayList<Status>();//存储该好友的微博
		String friend_id = uid + "";
		Paging page = new Paging();
		Timeline tm = new Timeline();
		try {
			page.setPage(1);
			StatusWapper status;
			try {
				status = tm.getUserTimelineByUid(friend_id, page,
						0, 1);
				for (Status s : status.getStatuses()) {
					statuslist.add(s);
				}
				page.setPage(2);
				StatusWapper status2 = tm.getUserTimelineByUid(friend_id, page,
						0, 1);
				for (Status s : status2.getStatuses()) {
					statuslist.add(s);
				}
			} catch (NullStatusException e) {
				// TODO Auto-generated catch block
				//Thread.sleep(1000 * 60);
				e.printStackTrace();
				System.err.println(uid);
				//return getStstusListByUID(uid);
			}
			//page.setPage(3);
			//StatusWapper status3 = tm.getUserTimelineByUid(friend_id, page,
				//	0, 1);
			//for (Status s : status3.getStatuses()) {
				//statuslist.add(s);
			//}
		} catch (WeiboException e) {
			e.printStackTrace();
		}			
		return statuslist;
	}
}
